cc.Class({
    extends: require('Component'),

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
        Frams : {
            default : [],
            type : cc.SpriteFrame,
            tooltip : '来回切换的图集'
        },
        attach :{
            default : [],
            type:cc.Node,
            tooltip:'当toggle触发修改时，本数组里的节点会受影响，可以为空'
        },
        clickEvents: {
            "default": [],
            type: cc.Component.EventHandler,
            tooltip: "i18n:COMPONENT.button.click_events"
        }
    },

    // use this for initialization
    onLoad: function () {
        // this.node.on(cc.Node.EventType.TOUCH_START, this.onTouch, this);
        if(this.clickEvents.length>0){
            this.registerTouch();
        }
        this.index = 0;
    },
    registerTouch(){
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouch, this); 
    },

    onTouch : function(event){
        if(this.clickEvents.length == 0)
            return;

        this.index++;
        event.toggle = this;
        // event.toggle.index = this.index;
        this.setToggle(this.index);
        
        cc.Component.EventHandler.emitEvents(this.clickEvents, event);
    },
    setToggle :function(index){
        this.index = index % this.Frams.length;
        this.node.getComponent(cc.Sprite).spriteFrame = this.Frams[this.index];
        if(this.attach.length > this.index){
            for(var i=0; i<this.attach.length; i++){
                this.attach[i].active = this.index == i;
            }
        }
    },
    getToggle(){
        return this.index;
    }

    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});
